<template>
  <div class="auth-container">
    <div class="auth-form">
      <h3 class="auth-title">智能售后工单处理与AI知识助手系统</h3>
      <el-form ref="loginFormRef" :model="loginState.loginForm" :rules="loginState.loginRules" status-icon>
        <el-form-item prop="username">
          <el-input 
            v-model="loginState.loginForm.username"
            placeholder="用户名" 
            :prefix-icon="UserFilled"
            name="username"
            autocomplete="username"
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input 
            v-model="loginState.loginForm.password" 
            type="password" 
            placeholder="密码" 
            :prefix-icon="Lock"
            name="password"
            autocomplete="current-password"
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        
        <el-form-item>
          <el-checkbox v-model="loginState.loginForm.rememberMe">记住我</el-checkbox>
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            class="auth-form-button" 
            :loading="loading" 
            @click="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="auth-form-footer">
        <span>没有账号?</span>
        <router-link to="/register">立即注册</router-link>
      </div>
      
      <div class="test-credentials">
        <p>系统管理员: admin / 123456</p>
        <p>其他角色账号: cs001, tech001, hw001, sw001, user001 (密码同上)</p>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { UserFilled, Lock } from '@element-plus/icons-vue'

export default {
  name: 'Login',
  setup() {
    const store = useStore()
    const router = useRouter()
    const route = useRoute()
    const loginFormRef = ref(null)
    
    const loginState = reactive({
      loginForm: {
        username: 'admin',  // 默认填写测试账号
        password: '123456', // 默认填写测试密码
        rememberMe: false
      },
      loginRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '用户名长度必须在3-20位之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度必须在6-20位之间', trigger: 'blur' }
        ]
      }
    })
    
    const loading = computed(() => store.state.loading)
    
    const handleLogin = () => {
      if (!loginFormRef.value) {
        console.error('loginFormRef is null')
        ElMessage.error('表单引用错误')
        return
      }
      
      // 打印登录表单数据
      console.log('登录表单数据:', {
        username: loginState.loginForm.username,
        passwordLength: loginState.loginForm.password ? loginState.loginForm.password.length : 0
      })
      
      loginFormRef.value.validate(async (valid) => {
        console.log('表单验证结果:', valid)
        
        if (valid) {
          try {
            // 确保输入不为空
            if (!loginState.loginForm.username || !loginState.loginForm.username.trim()) {
              ElMessage.error('用户名不能为空')
              return
            }
            
            if (!loginState.loginForm.password || !loginState.loginForm.password.trim()) {
              ElMessage.error('密码不能为空')
              return
            }
            
            // 创建一个新对象，确保数据干净
            const loginData = {
              username: loginState.loginForm.username.trim(),
              password: loginState.loginForm.password.trim(),
              rememberMe: !!loginState.loginForm.rememberMe
            }
            
            console.log('正在登录，用户名:', loginData.username)
            console.log('发送的登录数据:', JSON.stringify(loginData))
            
            const result = await store.dispatch('login', loginData)
            console.log('登录成功，返回数据:', result)
            
            // 验证用户信息是否存在
            const userInfo = JSON.parse(localStorage.getItem('user') || '{}')
            console.log('本地存储中的用户信息:', userInfo)
            
            if (!userInfo || !userInfo.username) {
              console.error('登录失败：未获取到用户信息')
              ElMessage.error('登录失败：用户信息无效')
              return
            }
            
            ElMessage.success('登录成功')
            
            // 立即进行路由跳转
            // 如果有重定向参数，跳转到该页面，否则跳转到默认页面
            const redirectPath = route.query.redirect || '/dashboard'
            console.log('正在跳转到:', redirectPath)
            
            // 确保路由跳转执行
            setTimeout(() => {
              router.push(redirectPath)
              console.log('路由跳转已执行')
            }, 100)
          } catch (error) {
            console.error('登录错误:', error)
            // 根据后端错误消息显示不同的提示
            let errorMsg = '登录失败，请检查用户名和密码'
            if (error.response && error.response.data && error.response.data.message) {
              errorMsg = error.response.data.message
            } else if (error.message) {
              errorMsg = error.message
            }
            ElMessage.error(errorMsg)
          }
        }
      })
    }
    
    onMounted(() => {
      // 如果已经登录，自动跳转到首页
      if (store.getters.isAuthenticated) {
        router.push('/dashboard')
      }
    })
    
    return {
      loginFormRef,
      loginState,
      loading,
      handleLogin,
      UserFilled,
      Lock
    }
  }
}
</script>

<style scoped>
.auth-form {
  text-align: center;
}

.test-credentials {
  margin-top: 20px;
  font-size: 12px;
  color: #909399;
}
</style> 
 